package com.jsz.peini.service.sign;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jsz.peini.bean.coupon.CouponInfo;
import com.jsz.peini.bean.coupon.CouponUser;
import com.jsz.peini.bean.order.GoldHistory;
import com.jsz.peini.bean.order.ScoreHistory;
import com.jsz.peini.bean.sign.SignInfo;
import com.jsz.peini.bean.sign.SignInfoExample;
import com.jsz.peini.bean.sign.SignSet;
import com.jsz.peini.bean.sign.SignSetDetail;
import com.jsz.peini.bean.sign.SignSetDetailExample;
import com.jsz.peini.bean.sign.SignSetExample;
import com.jsz.peini.bean.sign.SignSetExample.Criteria;
import com.jsz.peini.bean.user.UserAccount;
import com.jsz.peini.common.util.DateTimeUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.mapper.coupon.CouponGetMapper;
import com.jsz.peini.mapper.coupon.CouponInfoMapper;
import com.jsz.peini.mapper.order.GoldHistoryMapper;
import com.jsz.peini.mapper.order.ScoreHistoryMapper;
import com.jsz.peini.mapper.sign.SignInfoMapper;
import com.jsz.peini.mapper.sign.SignSetDetailMapper;
import com.jsz.peini.mapper.sign.SignSetMapper;
import com.jsz.peini.mapper.user.UserAccountMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.util.SignRedisUtil;
import com.jsz.peini.service.coupon.CouponInfoService;

@Service
public class SignInfoService {
	private static final Logger logger = LoggerFactory.getLogger(SignInfoService.class);
	@Resource
	private SignInfoMapper signInfoMapper;
	@Resource
	private GoldHistoryMapper goldHistoryMapper;
	@Resource
	private UserAccountMapper userAccountMapper;
	@Resource
	private SignSetMapper signSetMapper;
	@Resource
	private SignSetDetailMapper signSetDetailMapper;
	@Resource
	private CouponGetMapper couponGetMapper;
	@Resource
	private ScoreHistoryMapper scoreHistoryMapper;
	@Resource
	private CouponInfoMapper couponInfoMapper;
	@Resource
	private CouponInfoService couponInfoService;
	@Resource
	private UserInfoMapper userInfoMapper;
	
	public SignInfo selectTodayByUser(SignInfo signInfo){
		List<SignInfo> list = signInfoMapper.selectTodayByUser(signInfo);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}
	
	public int insert(SignInfo signInfo){
		int result = signInfoMapper.insert(signInfo);
		return result;
	}
	
	public List<HashMap<String,Object>> selectSignList(HashMap<String,Object> signMap){
		List<HashMap<String,Object>> signList= signInfoMapper.selectSignList(signMap);
		return signList;
	}
	
	/**
	 * 正常签到
	 * @author Han Guohong
	 * @param userId
	 * @param userAccount
	 * @return
	 */
	@Transactional
	public String nowSign(String userId,UserAccount userAccount){
		String str = "";
		try {
			SignInfo signInfo = new SignInfo();
			signInfo.setSignDate(new Date());
			signInfo.setIsAdd(0);
			signInfo.setUserId(userId);
			signInfoMapper.insert(signInfo);
			int signId = signInfo.getId();
			
			int signDays = SignRedisUtil.getSignDays(userId);
			signDays ++;
			SignRedisUtil.updateLastSignDate(userId, new Date());
			
			//查询是否如何连续签到规则
			SignSetExample example = new SignSetExample();
			Criteria criteria = example.createCriteria();
			criteria.andSettypeEqualTo(2);
			criteria.andIsreleaseEqualTo(1);
			criteria.andSuccessivedaysEqualTo(signDays);
			example.setOrderByClause("successivedays desc");
			List<SignSet> list = signSetMapper.selectByExampleWithBLOBs(example);
			if(list.size() > 0){
				SignSet set = list.get(0);
				
				String setId = set.getSetid();
				
				SignSetDetailExample detailExample = new SignSetDetailExample();
				com.jsz.peini.bean.sign.SignSetDetailExample.Criteria detCriteria = detailExample.createCriteria();
				detCriteria.andSetidEqualTo(setId);
				List<SignSetDetail> details = signSetDetailMapper.selectByExample(detailExample);
				
				for (SignSetDetail detail : details) {
					switch (detail.getAwardtype()) {
					case 1:
						CouponInfo couponInfo = couponInfoMapper.getCouponInfoSignAward();
						if(couponInfo != null){
							List<CouponInfo> couponList = new ArrayList<CouponInfo>();
							for (int i = 0; i < detail.getAwardval(); i++) {
								/*CouponUser couponUser = new CouponUser();
								couponUser.setCouponId(couponInfo.getId());
								couponUser.setCouponNum(1);
								couponUser.setGetType(2);
								couponUser.setUserId(userId);*/
								
								couponList.add(couponInfo);
							}
							couponInfoService.rushBuyCouponResult(couponList, userId, 2,null);
						}
						break;
					case 2://金币
						Integer gold = userAccount.getGold();
						GoldHistory history = new GoldHistory();
						history.setCreateTime(new Date());
						history.setHisId(UUID.randomUUID().toString().replace("-", ""));
						history.setHisType(1);
						history.setIsDel(1);
						history.setIsFinish(1);
						history.setOpType(1);
						history.setParamId(String.valueOf(signId));
						history.setUserId(userId);
						
						BigDecimal valNum = new BigDecimal(detail.getAwardval());
						valNum = valNum.multiply(new BigDecimal("100"));
						
						history.setValNum(valNum.longValue());
						goldHistoryMapper.insertSelective(history);	
						
						userAccount.setGold(gold + valNum.intValue());
						userAccountMapper.updateByPrimaryKey(userAccount);
						break;
					case 3://积分
						ScoreHistory his = new ScoreHistory();
						his.setHisId(UUID.randomUUID().toString().replace("-", ""));
						his.setCreateTime(new Date());
						his.setUserId(userId);
						his.setOpType(1);
						his.setIsFinish(1);
						his.setValNum((long)detail.getAwardval());
						his.setHisType(1);
						his.setParamId(String.valueOf(signId));
						his.setIsDel(1);
						scoreHistoryMapper.insertSelective(his);
						
						Integer score = userAccount.getScore();
						userAccount.setScore(score+detail.getAwardval());
						userAccountMapper.updateByPrimaryKey(userAccount);
						
				        SmsSendUtil.sendSmsNotify(userId, userId, 113, "恭喜！您通过“签到”获得"+detail.getAwardval()+"积分，您当前总积分"+userAccount.getScore()+"，快去积分商城兑换吧~");
						break;
					default:
						break;
					}
				}
				
				str += set.getMarkedwords();
			}else{
				//查询是否符合单日签到规则
				example = new SignSetExample();
				criteria = example.createCriteria();
				criteria.andSetdateLessThanOrEqualTo(new Date());
				criteria.andEnddateGreaterThanOrEqualTo(new Date());
				criteria.andSettypeEqualTo(1);
				example.setOrderByClause("createtime desc");
				list = signSetMapper.selectByExampleWithBLOBs(example);
				if(list.size() > 0){
					SignSet set = list.get(0);
					
					String setId = set.getSetid();
					
					SignSetDetailExample detailExample = new SignSetDetailExample();
					com.jsz.peini.bean.sign.SignSetDetailExample.Criteria detCriteria = detailExample.createCriteria();
					detCriteria.andSetidEqualTo(setId);
					List<SignSetDetail> details = signSetDetailMapper.selectByExample(detailExample);
					
					for (SignSetDetail detail : details) {
						switch (detail.getAwardtype()) {
							case 1:
								CouponInfo couponInfo = couponInfoMapper.getCouponInfoSignAward();
								if(couponInfo != null){
									List<CouponInfo> couponList = new ArrayList<CouponInfo>();
									for (int i = 0; i < detail.getAwardval(); i++) {
										CouponUser couponUser = new CouponUser();
										couponUser.setCouponId(couponInfo.getId());
										couponUser.setCouponNum(1);
										couponUser.setGetType(2);
										couponUser.setUserId(userId);
										
										//PeiniUtils.couponUsers.add(couponUser);
										couponList.add(couponInfo);
									}
									couponInfoService.rushBuyCouponResult(couponList, userId, 2,null);
								}
								
								break;
							case 2://金币
								Integer gold = userAccount.getGold();
								GoldHistory history = new GoldHistory();
								history.setCreateTime(new Date());
								history.setHisId(UUID.randomUUID().toString().replace("-", ""));
								history.setHisType(1);
								history.setIsDel(1);
								history.setIsFinish(1);
								history.setOpType(1);
								history.setParamId(String.valueOf(signId));
								history.setUserId(userId);
								
								BigDecimal valNum = new BigDecimal(detail.getAwardval());
								valNum = valNum.multiply(new BigDecimal("100"));
								
								history.setValNum(valNum.longValue());
								goldHistoryMapper.insertSelective(history);	
								
								userAccount.setGold(gold + valNum.intValue());
								userAccountMapper.updateByPrimaryKey(userAccount);
								break;
							case 3://积分
								ScoreHistory his = new ScoreHistory();
								his.setHisId(UUID.randomUUID().toString().replace("-", ""));
								his.setCreateTime(new Date());
								his.setUserId(userId);
								his.setOpType(1);
								his.setIsFinish(1);
								his.setValNum((long)detail.getAwardval());
								his.setHisType(1);
								his.setParamId(String.valueOf(signId));
								his.setIsDel(1);
								scoreHistoryMapper.insertSelective(his);
								
								Integer score = userAccount.getScore();
								userAccount.setScore(score+detail.getAwardval());
								userAccountMapper.updateByPrimaryKey(userAccount);
								
								SmsSendUtil.sendSmsNotify(userId, userId, 113, "恭喜！您通过“签到”获得"+detail.getAwardval()+"积分，您当前总积分"+userAccount.getScore()+"，快去积分商城兑换吧~");
								break;
							default:
								break;
						}
					}
					
					str = set.getMarkedwords();
				}else{
					
				}
			}
			RedisUtil.hset(RedisConstants.SIGN_DAYS.getBytes(), userId.getBytes(), String.valueOf(signDays).getBytes());
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw e;
		}
		return str;
	}
	
	/**
	 * 补签到
	 * @author Han Guohong
	 * @param setDate
	 * @param userId
	 * @return
	 */
	@Transactional
	public String addSignInfo(String setDate,String userId,UserAccount userAccount){
		String str = "";
		try {
			SignInfo signInfo = new SignInfo();
			signInfo.setSignDate(DateTimeUtils.formatString2Date(setDate, "yyyy-MM-dd"));
			signInfo.setIsAdd(1);
			signInfo.setUserId(userId);
			signInfoMapper.insert(signInfo);
			int signId = signInfo.getId();
			
			
			//查询第几次补签
			SignInfoExample infoExample = new SignInfoExample();
			com.jsz.peini.bean.sign.SignInfoExample.Criteria infoCriteria = infoExample.createCriteria();
			infoCriteria.andUserIdEqualTo(userId);
			infoCriteria.andIsAddEqualTo(1);
			Integer cnt = signInfoMapper.countByExample(infoExample);
			cnt ++;
			
			//扣除相应的金币数量
			Integer gold = userAccount.getGold();
			GoldHistory history = new GoldHistory();
			history.setCreateTime(new Date());
			history.setHisId(UUID.randomUUID().toString().replace("-", ""));
			history.setHisType(3);
			history.setIsDel(1);
			history.setIsFinish(1);
			history.setOpType(0);
			history.setParamId(String.valueOf(signId));
			history.setUserId(userId);
			history.setValNum((long)cnt);
			goldHistoryMapper.insertSelective(history);	
			
			userAccount.setGold(gold - cnt);
			userAccountMapper.updateByPrimaryKey(userAccount);
			str = "第"+cnt+"次补签到扣除金币"+cnt;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw e;
		}
		return str;
	}

}
